package com.example;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.dao.UserDao;
import com.example.entity.User;

@Controller
@SpringBootApplication
@ServletComponentScan
@EnableScheduling
public class DemoApplication  {
	
	@Autowired
	private UserDao userDao;
	
	@RequestMapping("/success")
	public String success(){
		return "success";
	}
	@RequestMapping("/login")
	public String login(){
		return "loginPage";
	}
	@RequestMapping("/index")
	public String index(HttpServletRequest request){
//		User user=userDao.findByName(request.getParameter("name"));
		List<User> users=userDao.findUser(request.getParameter("name"), "");
		request.setAttribute("a", users.size());
		
		return "test/index1";
	}
	@RequestMapping("/myError")
	public String error(){
		return "error1";
	}
	
	@RequestMapping("/get-by-email")
    @ResponseBody
    public String getByEmail(String email) {
      String userId;
      User user = userDao.findByEmail("haha@haha");
      if (user != null) {
        userId = String.valueOf(user.getId());
        return "The user id is: " + userId;
      }
      return "user " + email + " is not exist.";
    }
	
	
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
	
	@Bean
	public EmbeddedServletContainerCustomizer containerCustomizer() {

	   return (container -> {
	        ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/myError");
	        ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/myError");
	        ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/myError");
	        container.addErrorPages(error401Page, error404Page, error500Page);
	   });
//		return new EmbeddedServletContainerCustomizer(){
//			@Override
//			public void customize(ConfigurableEmbeddedServletContainer container) {
//		        ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
//		        ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
//		        ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
//				container.addErrorPages(error401Page,error404Page,error500Page);
//			}
//		};
	}
}
